import loginRTM from "./rtmToken.js";
import { header, channel_file_name } from "./createRoom.js";
import loading from "/js/loading.js";
import { getWeekDate, getTime, formatDateArray, getDate } from "/js/util.js";

let client1,
  count = 0,
  channel_file = null, //文件频道
  offsetChannel = 0,
  start = getDate(new Date(), 7),
  end = formatDateArray(new Date()),
  start_time = `${start.y}-${start.month}-${start.d}T${start.h}:${start.minute}:${start.s}Z`,
  end_time = `${end.y}-${end.month}-${end.d}T${end.h}:${end.minute}:${end.s}Z`;

let loginAgora = async () => {
  let { client, channel2 } = await loginRTM();
  await channel2.join().then((res) => {
    console.log(res, "You have successfully joined channel");
  });

  channel2.on("ChannelMessage", async function (message, memberId, r) {
      let div = document.createElement('div')
      div.innerHTML = message.text
      let media = div.children[0].dataset.media;
      let name = div.children[0].children[0].innerText
      let size = div.children[0].children[1].innerText
      let li = document.createElement("li");
      li.className = "detail-file-ul-li";
      li.title = "download";
      li.dataset.media = media;
      li.dataset.filename = name;
      li.innerHTML = `
                <div class='detail-file-ul-filename' data-media=${media} data-filename=${name}>${name}</div>
                <div class='detail-file-ul-size' data-media=${media} data-filename=${name}>${size}</div>
            `;
      $(".detail-content")[0].appendChild(li);
  });

  channel_file = channel2;
  client1 = client;
};

let createFileWrap = async () => {
  $(".detail-content")[0] && $(".detail-content")[0].remove();
  let section_content = document.createElement("ul");
  section_content.className = "detail-content";
  await loginAgora();
  await getHistoryCount();
  let list = await getFileHistory();
  createFileList(list, section_content);
  $(".section-course_history-detail")[0].appendChild(section_content);
  createUlLiListener();
};

let getHistoryCount = async () => {
  let recentlyChannel = await $.ajax({
    url: "https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/count",
    headers: header,
    async: true, //异步或同步，默认异步
    dataType: "json", //服务器返回类型
    data: {
      destination: channel_file_name,
      start_time,
      end_time,
    },
    type: "get",
  }).then(async (res) => {
    return res.count;
  });
  count = recentlyChannel;
};

let getFileHistory = async (destination = channel_file_name, offsetChannel) => {
  let list = await $.ajax({
    url: "https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query",
    data: JSON.stringify({
      filter: {
        destination,
        start_time,
        end_time,
      },
      offset: offsetChannel,
      limit: 100,
    }),
    headers: header,
    async: true, //异步或同步，默认异步
    dataType: "json", //服务器返回类型
    type: "post",
  })
    .then(async (res) => {
      let { location } = res;
      location = location.split("/")[5];
      let list = await $.ajax({
        url: `https://api.agora.io/dev/v2/project/69ee1d0f77224d1897d21a1d3bc56cd4/rtm/message/history/query/${location}`,
        type: "get",
        headers: header,
        dataType: "json",
        async: true,
      });
      list.messages.forEach((item) => {
        let div = document.createElement("div");
        div.innerHTML = item.payload;
        let media = div.children[0].dataset.media;
        item.media = media;
        item.name = div.children[0].children[0].innerText;
        item.size = div.children[0].children[1].innerText.replace("\n", "");
      });
      return list.messages;
    })
    .catch((err) => {
      console.log(err);
    });
  return list;
};

let createFileList = (list, section_content) => {
  for (let i = 0; i < list.length; i++) {
    let li = document.createElement("li");
    li.className = "detail-file-ul-li";
    li.title = "download";
    li.dataset.media = list[i].media;
    li.dataset.filename = list[i].name;
    li.innerHTML = `
            <div class='detail-file-ul-filename' data-media=${list[i].media} data-filename=${list[i].name}>${list[i].name}</div>
            <div class='detail-file-ul-size' data-media=${list[i].media} data-filename=${list[i].name}>${list[i].size}</div>
        `;
    section_content.appendChild(li);
  }
};

let createUlLiListener = () => {
  $(".detail-file-ul-li").each(function (index) {
    $(this).on("click", async function (e) {
      let { media, filename } = e.target.dataset;
      const blob = await client1.downloadMedia(media);
      saveAs(blob, filename);
    });
  });
};

let appendFileFoot = (res) => {
  let frag = document.createDocumentFragment();
  createFileList(res, frag);
  $(".detail-content")[0].appendChild(frag);
};

let listenerScrollFoot = () => {
    $('.detail-content')[0].addEventListener('scroll',async (e) => {
        if(e.target.scrollTop === $('.detail-content')[0].scrollHeight){
          offsetChannel += 100
          if(count < offsetChannel) {return}
          let list = await getFileHistory()
          appendFileFoot(list)
        }
    })
}


export { createFileWrap };
